package com.xiaot.shopping.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaot.common.utils.PageUtils;
import com.xiaot.common.utils.Query;
import com.xiaot.shopping.product.dao.AttrAttrgroupRelationDao;
import com.xiaot.shopping.product.dao.AttrGroupDao;
import com.xiaot.shopping.product.dao.CategoryDao;
import com.xiaot.shopping.product.entity.AttrGroupEntity;
import com.xiaot.shopping.product.entity.CategoryEntity;
import com.xiaot.shopping.product.service.AttrGroupService;
import com.xiaot.shopping.product.vo.AttrGroupRelationVo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Resource
    private CategoryDao categoryDao;
    @Resource
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catId) {
        String key = (String) params.get("key");
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<AttrGroupEntity>();
        if (catId != 0) {
            wrapper.eq("catelog_id", catId);
        }
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((obj) -> {
                obj.eq("attr_group_id", key).or().like("attr_group_name", key);
            });
        }
        return new PageUtils(this.page(new Query<AttrGroupEntity>().getPage(params), wrapper));
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> cateLogPath = findCateLogPath(catelogId, new ArrayList<>());
        Collections.reverse(cateLogPath);
        return cateLogPath.toArray(new Long[0]);
    }

    private List<Long> findCateLogPath(Long catId, List<Long> cateLogPath) {
        cateLogPath.add(catId);
        CategoryEntity entity = categoryDao.selectById(catId);
        if (!entity.getParentCid().equals(0L)) {
            findCateLogPath(entity.getParentCid(), cateLogPath);
        }
        return cateLogPath;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] attrGroupRelation) {
        List<AttrGroupRelationVo> attrGroupRelationList = Arrays.asList(attrGroupRelation);
        attrAttrgroupRelationDao.deleteRelation(attrGroupRelationList);

    }
}